<route lang="json5">
{
  style: {
    navigationBarTitleText: '注册',
  },
}
</route>

<template>
  <view class="register-container">
    <view class="form-container">
      <wd-cell-group>
        <!-- 手机号输入 -->
        <wd-input
          v-model="form.phone"
          label="手机号"
          placeholder="请输入手机号"
          type="number"
          maxlength="11"
          :error="errors.phone"
          :error-message="errors.phoneMessage"
          @blur="validatePhone"
        >
          <template #prefix>
            <text class="iconfont icon-phone"></text>
          </template>
        </wd-input>

        <!-- 验证码输入 -->
        <wd-input
          v-model="form.code"
          label="验证码"
          placeholder="请输入验证码"
          type="number"
          maxlength="6"
          :error="errors.code"
          :error-message="errors.codeMessage"
          @blur="validateCode"
        >
          <template #prefix>
            <text class="iconfont icon-shield"></text>
          </template>
          <template #suffix>
            <wd-button
              size="small"
              :disabled="!!countdown || !form.phone || errors.phone"
              @click="handleSendCode"
            >
              {{ countdown ? `${countdown}s后重新获取` : '获取验证码' }}
            </wd-button>
          </template>
        </wd-input>

        <!-- 密码输入 -->
        <wd-input
          v-model="form.password"
          label="密码"
          placeholder="请输入密码"
          :type="showPassword ? 'text' : 'password'"
          :error="errors.password"
          :error-message="errors.passwordMessage"
          @blur="validatePassword"
        >
          <template #prefix>
            <text class="iconfont icon-lock"></text>
          </template>
          <template #suffix>
            <text
              class="iconfont"
              :class="showPassword ? 'icon-eye' : 'icon-eye-close'"
              @click="togglePasswordVisibility"
            ></text>
          </template>
        </wd-input>

        <!-- 确认密码 -->
        <wd-input
          v-model="form.confirmPassword"
          label="确认密码"
          placeholder="请再次输入密码"
          :type="showConfirmPassword ? 'text' : 'password'"
          :error="errors.confirmPassword"
          :error-message="errors.confirmPasswordMessage"
          @blur="validateConfirmPassword"
        >
          <template #prefix>
            <text class="iconfont icon-lock"></text>
          </template>
          <template #suffix>
            <text
              class="iconfont"
              :class="showConfirmPassword ? 'icon-eye' : 'icon-eye-close'"
              @click="toggleConfirmPasswordVisibility"
            ></text>
          </template>
        </wd-input>
      </wd-cell-group>

      <!-- 注册按钮 -->
      <view class="button-container">
        <wd-button type="primary" block @click="handleRegister" :loading="loading">
          注册
        </wd-button>
      </view>

      <!-- 登录链接 -->
      <view class="login-link">
        <text>已有账号？</text>
        <text class="link" @click="navigateToLogin">立即登录</text>
      </view>
    </view>

    <!-- 注册协议 -->
    <view class="agreement">
      <wd-checkbox v-model="form.agreement" @change="handleAgreementChange">
        我已阅读并同意
      </wd-checkbox>
      <text class="link" @click="showUserAgreement">《用户协议》</text>
      <text>和</text>
      <text class="link" @click="showPrivacyPolicy">《隐私政策》</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, onUnmounted } from 'vue'
import { showToast } from '@/utils/toast'
import { register, sendCode } from '@/api/auth'

const form = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
  agreement: false,
})

const errors = reactive({
  phone: false,
  phoneMessage: '',
  code: false,
  codeMessage: '',
  password: false,
  passwordMessage: '',
  confirmPassword: false,
  confirmPasswordMessage: '',
})

const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const countdown = ref(0)
let countdownTimer: number | null = null

// 表单验证
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!form.phone) {
    errors.phone = true
    errors.phoneMessage = '请输入手机号'
    return false
  }
  if (!phoneRegex.test(form.phone)) {
    errors.phone = true
    errors.phoneMessage = '请输入正确的手机号'
    return false
  }
  errors.phone = false
  errors.phoneMessage = ''
  return true
}

const validateCode = () => {
  if (!form.code) {
    errors.code = true
    errors.codeMessage = '请输入验证码'
    return false
  }
  if (form.code.length !== 6) {
    errors.code = true
    errors.codeMessage = '验证码长度不正确'
    return false
  }
  errors.code = false
  errors.codeMessage = ''
  return true
}

const validatePassword = () => {
  if (!form.password) {
    errors.password = true
    errors.passwordMessage = '请输入密码'
    return false
  }
  if (form.password.length < 6) {
    errors.password = true
    errors.passwordMessage = '密码长度不能小于6位'
    return false
  }
  errors.password = false
  errors.passwordMessage = ''
  return true
}

const validateConfirmPassword = () => {
  if (!form.confirmPassword) {
    errors.confirmPassword = true
    errors.confirmPasswordMessage = '请再次输入密码'
    return false
  }
  if (form.confirmPassword !== form.password) {
    errors.confirmPassword = true
    errors.confirmPasswordMessage = '两次输入的密码不一致'
    return false
  }
  errors.confirmPassword = false
  errors.confirmPasswordMessage = ''
  return true
}

const validateForm = () => {
  return (
    validatePhone() &&
    validateCode() &&
    validatePassword() &&
    validateConfirmPassword()
  )
}

// 发送验证码
const handleSendCode = async () => {
  if (!validatePhone()) {
    return
  }

  try {
    loading.value = true
    await sendCode({
      phone: form.phone,
      type: 'register'
    })
    showToast('验证码发送成功')
    startCountdown()
  } catch (error) {
    showToast(error.message || '验证码发送失败，请重试')
  } finally {
    loading.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(countdownTimer!)
      countdownTimer = null
    }
  }, 1000)
}

// 处理注册
const handleRegister = async () => {
  if (!form.agreement) {
    showToast('请先同意用户协议和隐私政策')
    return
  }

  if (!validateForm()) {
    return
  }

  loading.value = true
  try {
    await register({
      phone: form.phone,
      code: form.code,
      password: form.password,
      confirmPassword: form.confirmPassword
    })
    
    showToast('注册成功')
    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/login/index'
      })
    }, 1500)
  } catch (error) {
    showToast(error.message || '注册失败，请重试')
  } finally {
    loading.value = false
  }
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value
}

// 处理协议变更
const handleAgreementChange = (value: boolean) => {
  form.agreement = value
}

// 页面跳转
const navigateToLogin = () => {
  uni.navigateBack()
}

// 显示协议
const showUserAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement/user',
  })
}

const showPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages/agreement/privacy',
  })
}

// 组件销毁时清理倒计时
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style lang="scss">
.register-container {
  min-height: 100vh;
  padding: 20px;
  background-color: #fff;
}

.form-container {
  margin-top: 20px;
}

.button-container {
  margin: 40px 0 20px;
}

.login-link {
  text-align: center;
  font-size: 14px;
  color: #666;

  .link {
    color: #4a90e2;
    margin-left: 4px;
  }
}

.agreement {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 40px;
  text-align: center;
  font-size: 12px;
  color: #666;
  padding: 0 30px;

  .link {
    color: #4a90e2;
  }
}
</style>
